package com.pzhyd.sc.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/** 
 * @Project: webvote
 * @Title: Uploadfiles.java
 * @Package com.pzhyd.sc.util
 * @Description: TODO
 * @author Gaoshiwei 812257531@qq.com
 * @date Jul 13, 2012 10:49:32 AM
 * @Copyright: 2012 攀枝花移动 All rights reserved.
 * @version V1.0  
 */
public class Uploadfiles extends HttpServlet {
	
	//上传文件到服务器

	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, java.io.IOException{
		request.setCharacterEncoding("UTF-8");
		// 设置上传路径
		String realPath = request.getSession().getServletContext().getRealPath("/upload");
		UploadUtil.setUploadPath(realPath);
		System.out.println("获取服务器路径："+realPath);
		try {
			// 文件上传部分
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if (isMultipart == true) {//判断是否为多文件上传
				FileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				
				// 得到所有的表单域，它们目前都被当作FileItem
				List<FileItem> fileItems = upload.parseRequest(request);
				Iterator<FileItem> iter = fileItems.iterator();
				// 依次处理每个表单域
				while (iter.hasNext()) {
					FileItem item = (FileItem) iter.next();
					if(item.isFormField()){
						// 如果item是正常的表单域
						String name = item.getFieldName();
					    String value = item.getString();
					    System.out.print("表单域名为:"+name+"表单域值为:"+value);
					    //
					   
					}
					else{
						// 如果item是文件上传表单域
						// 获得文件名及路径
						String fileName = item.getName();
						if (fileName != null) {
							File fullFile = new File(item.getName());												
							// 如果文件存在则在后面加上当前时间再上传，否则直接上传
							if(fullFile.exists()){
								String tempname=fullFile.getName();
								String filename=tempname.substring(0, tempname.lastIndexOf("."))+
								new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"."+
								tempname.substring(tempname.lastIndexOf(".") + 1);
								File fileOnServer = new File(UploadUtil.getUploadPath(),
										filename);
								item.write(fileOnServer);
								System.out.println("文件"+fileOnServer.getName()+"上传成功");
							
								response.getWriter().write("<script>parent.callback('"+fileOnServer.getName()+"')</script>");
							}
							else{
								File fileOnServer = new File(UploadUtil.getUploadPath(),
										fullFile.getName());
								item.write(fileOnServer);
								System.out.println("文件"+fileOnServer.getName()+"上传成功");
								
								response.getWriter().write("<script>parent.callback('"+fileOnServer.getName()+"')</script>");
							}
							
						}
					}
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, java.io.IOException {
		doPost(request, response);
	}
}
